<template>
  <view class="page">
    <!-- 搜索 -->
    <!-- <view class="search-box">
      <view class="search">
        <text class="iconfont icon-sousuo"></text>
        <input
          type="text"
          placeholder="搜索商品"
          v-model="keyword"
          @input="handleInput"
        />
      </view>
    </view> -->
    <view class="head-box">
      <view
        class="serch-box"
        :style="{
          paddingTop: statusBarHeight + 'px',
          height: statusBarHeight + titleBarHeight + 5 + 'px'
        }"
      >
        <view class="title" :style="{ height: titleBarHeight + 'px' }">
          <view class="search-input">
            <text class="iconfont icon-sousuo"></text>
            <input type="text" placeholder="搜索商品" v-model="keyword" @input="handleInput" />
          </view>
          <view class="contact">
            <text class="iconfont icon-xiaoxi"></text>
            <button open-type="contact"></button>
          </view>
        </view>
      </view>
    </view>
    <!-- 轮播图 -->
    <view
      class="swiper-box"
      v-if="swiperList.length"
      :style="{ marginTop: -(statusBarHeight + titleBarHeight - 5) + 'px' }"
    >
      <u-swiper
        mode="dot"
        height="260"
        name="image"
        :list="swiperList"
        @click="previewSwiper"
      ></u-swiper>
    </view>
    <!-- 商品分类 -->
    <view class="category-box">
      <swiper indicator-dots indicator-color="#ddd" indicator-active-color="#FE492F">
        <swiper-item v-for="(item, index) in goodsCategoryList" :key="index">
          <view
            class="category-item"
            @tap="goodsType(item1.id, item1.name)"
            v-for="item1 in item"
            :key="item1.id"
          >
            <image :src="item1.image" />
            <view class="item-name">{{ item1.name }}</view>
          </view>
        </swiper-item>
      </swiper>
    </view>
    <!-- 底部 -->
    <view class="bottom-box">
      <!-- 公告 -->
      <view class="notice-box" @tap="showNotice = true">
        <view class="notice-img">
          <image :src="noticeImg" />
        </view>
        <view class="notice-title">公告</view>
        <view class="notice-scroll">
          <noticeBar
            color="#999999"
            background-color="#fff"
            :scrollable="true"
            :single="true"
            :text="noticeText"
          ></noticeBar>
        </view>
      </view>
      <!-- 特价促销 -->
      <template v-if="saleList.length">
        <view class="sale-box">
          <view class="sale-top">
            <image :src="require('@/static/image/特价促销.png')" mode="widthFix" />
          </view>
          <view class="sale-bottom">
            <scroll-view @scrolltolower="saleScroll" enable-flex class="sale-goods-box" scroll-x>
              <view class="sale-items" v-for="item in saleList" :key="item.id">
                <view class="sale-item" @tap="getDetail(item.id)">
                  <image :src="item.goods_image" mode="aspectFill" />
                  <view class="sale-money" v-if="priceStatus">
                    <text>￥</text>
                    <text>{{ item.price }}</text>
                    <text>{{ item.decimal ? '.' + item.decimal : '' }}</text>
                  </view>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
      </template>
      <!-- 商品分类tabs -->
      <view class="tabs-box">
        <u-tabs
          bg-color="#f7f7f7"
          font-size="32"
          bar-width="44"
          inactive-color="#666666"
          active-color="#111111"
          :list="goodsTypeList"
          :current="current"
          @change="change"
          :bar-style="{ backgroundColor: '#FE492F' }"
        ></u-tabs>
      </view>
      <!-- 空缺页 -->
      <dht-empty v-if="noData" type="no_data"></dht-empty>
      <!-- 商品 -->
      <view class="goods-box">
        <view class="bottom" :style="{ paddingBottom: userInfo.binding == 1 ? '' : '150rpx' }">
          <view class="goods-box">
            <view class="item" @tap="getDetail(item.id)" v-for="item in goodsList" :key="item.id">
              <view class="item-img">
                <image :src="item.goods_image" mode="scaleToFill" />
              </view>
              <view class="item-name">{{ item.goods_name }}</view>
              <view class="item-price">
                <view class="price">
                  <view
                    class="price-box"
                    v-if="userInfo.binding == 1 && item.price !== '' && priceStatus"
                  >
                    <text class="price1">￥</text>
                    <text class="price2">{{ item.price }}</text>
                    <text class="digit">.{{ item.decimal }}</text>
                  </view>
                </view>
                <view class="t-icon t-icon-a-" @tap.stop="showPop(item)"></view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 绑定手机提示 -->
    <view class="bandTip" v-if="userInfo.binding == 2">
      <view>绑定手机后可看价格</view>
      <view @tap="bandPhone">去绑定</view>
    </view>
    <!-- 选择规格弹出框 -->
    <pop-choose :goods="goods" v-model="show"></pop-choose>
    <!-- 公告弹出框 -->
    <u-popup @close="close" border-radius="20" width="602" v-model="showNotice" mode="center">
      <view class="pop-box">
        <view class="pop-top">公告</view>
        <view class="pop-center">{{ noticeText }}</view>
        <view class="pop-bottom">
          <view @tap="showNotice = false">知道了</view>
        </view>
      </view>
    </u-popup>
    <!-- 用户信息修改 -->
    <userinfoPopup @save="popForm.save" @close="popForm.close" :form="popForm"></userinfoPopup>
  </view>
</template>

<script>
import noticeBar from '@/components/uni-notice-bar'
import userinfoPopup from './userinfoPopup.vue'
import { mapState } from 'vuex'

export default {
  components: {
    noticeBar,
    userinfoPopup
  },
  data() {
    return {
      statusBarHeight: '', // 状态栏高度
      titleBarHeight: '', // 标题栏高度
      // 空白页
      noData: false,
      // 促销
      saleList: [],
      salePage: 1,
      id: '',
      userInfo: null,
      swiperList: [],
      swiperImageList: [],
      noticeImg: require('@/static/image/喇叭.png'),
      goodsCategoryList: [],
      goodsTypeList: [],
      goodsList: [],
      page: 1,
      hasMore: true,
      keyword: '',
      timeId: '',
      show: false,
      goods: null,
      showNotice: false,
      noticeText: '',
      current: 0,
      popForm: {
        show: false,
        close: () => {
          this.popForm.show = false
        },
        save: async (formData) => {
          console.log('保存的数据', formData)
          let res = await this.$http.post('/api/kuerp/order/user/profile', formData)
          console.log('保存成功', res)
          if (res.code == 1) {
            this.popForm.show = false
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
            const userInfo = await this.getUserInfo()
            uni.setStorageSync('userInfo', userInfo)
          }
        },
        data: {
          avatar: '',
          nickname: ''
        }
      }
    }
  },
  onReady() {
    uni.getSystemInfo({
      success: (e) => {
        // #ifdef MP-WEIXIN
        const custom = wx.getMenuButtonBoundingClientRect()
        const statusBarHeight = e.statusBarHeight // 状态栏高度
        this.statusBarHeight = statusBarHeight
        const titleBarHeight = custom.height + (custom.top - statusBarHeight) * 2 // 标题栏高度
        this.titleBarHeight = titleBarHeight
        // #endif
      }
    })
  },
  async onLoad() {
    this.getPageName()
    this.getSwiper()
    await this.getGoodsCategory()
    this.id = this.goodsTypeList[0].id

    this.saleList = []
    this.salePage = 1
    this.getSale()

    this.getGoods()
    this.getNotice()
    this.getPriceStatus()
    wx.showShareMenu({
      menus: ['shareAppMessage'] //shareAppMessage必须得有
    })
  },
  onShow() {
    this.userInfo = uni.getStorageSync('userInfo')
    if (uni.getStorageSync('loginFlag') && this.userInfo.nickname == '微信用户') {
      this.popForm.show = true
    }
    uni.removeStorageSync('loginFlag')
    this.getCartNumber()
  },
  onReachBottom() {
    if (!this.hasMore) return
    this.page++
    this.getGoods()
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      const res = await this.$http.post('/api/kuerp/order/user/userInfo')
      if (res.code == 200) return res.data.userinfo
    },
    // 滚动到右侧
    saleScroll() {
      this.salePage++
      this.getSale()
    },
    // 获取特价促销列表
    async getSale() {
      let postForm = {
        page: this.salePage,
        promotion: 1
      }
      const res = await this.$http.post('/api/kuerp/order/index/goodsGoodsList', postForm)
      if (res.code == 200) {
        res.data.list.forEach((item) => {
          item.goods_image = item.goods_image.startsWith('http')
            ? item.goods_image
            : this.$baseURL + item.goods_image
          this.saleList.push(item)
        })
      }
    },
    // 获取标题
    async getPageName() {
      const res = await this.$http.post('/api/kuerp/order/config/getdetail', {
        name: 'indextitle'
      })
      if (res.code == 200) {
        uni.setNavigationBarTitle({ title: res.data[0].value })
      }
    },
    // 获取公告
    async getNotice() {
      const res = await this.$http.post('/api/kuerp/order/config/getdetail', {
        name: 'notice'
      })
      if (res.code == 200) {
        this.noticeText = res.data[0].value
      }
    },
    // 是否显示价格
    async getPriceStatus() {
      const res = await this.$http.post('/api/kuerp/order/config/getdetail', {
        name: 'price_status'
      })
      if (res.code == 200) {
        this.$store.commit('setPriceStatus', res.data[0].value == 1)
      }
    },
    // tabs 改变
    change(index) {
      this.current = index
      this.id = this.goodsTypeList[index].id
      this.page = 1
      this.hasMore = true
      this.keyword = ''
      this.goodsList = []
      this.getGoods()
    },

    // 预览轮播图
    previewSwiper(index) {
      uni.previewImage({
        current: index,
        urls: this.swiperImageList
      })
    },
    // 关闭公告
    close() {
      uni.setStorageSync('showNotice', false)
      this.showNotice = false
    },
    // 获取购物车数量
    async getCartNumber() {
      const res = await this.$http.post('/api/kuerp/order/index/getCartNumber', false)
      if (res.code == 200) {
        if (res.data === 0) {
          uni.removeTabBarBadge({ index: 2 })
        } else {
          uni.setTabBarBadge({
            index: 2,
            text: res.data + ''
          })
        }
      }
    },
    // 弹出框
    showPop(goods) {
      this.goods = goods
      this.show = true
    },
    // 搜索商品
    handleInput() {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(() => {
        this.goodsList = []
        this.page = 1
        this.hasMore = true
        this.getGoods()
      }, 1000)
    },
    // 点击绑定手机号
    bandPhone() {
      uni.navigateTo({
        url: '/pages/my/commonFunction/accountManagement/bindPhone'
      })
    },
    // 获取轮播图
    async getSwiper() {
      const res = await this.$http.post('/api/kuerp/order/index/banner', {
        type_id: 1
      })
      if (res.code == 200) {
        res.data.forEach((item) => {
          item.image = item.image.startsWith('http') ? item.image : this.$baseURL + item.image
          this.swiperImageList.push(item.image)
        })
        this.swiperList = res.data
      } else {
        uni.hideToast()
      }
    },
    // 获取商品分类
    async getGoodsCategory() {
      const res = await this.$http.post('/api/kuerp/order/index/goodsTypeList')
      if (res.code == 200) {
        this.goodsTypeList = res.data

        let temp = []
        res.data.forEach((item, index) => {
          item.image = item.image.startsWith('http') ? item.image : this.$baseURL + item.image
          temp.push(item)
          if (((index + 1) % 5 === 0 && index !== 0) || index === res.data.length - 1) {
            this.goodsCategoryList.push(temp)
            temp = []
          }
        })
      }
    },
    // 获取商品列表
    async getGoods() {
      const res = await this.$http.post('/api/kuerp/order/index/goodsGoodsList', {
        goods_type_id: this.id,
        keyword: this.keyword,
        page: this.page
      })
      if (res.code == 200) {
        if (res.data.list.length === 0) this.hasMore = false

        res.data.list.forEach((item) => {
          item.goods_image = item.goods_image.startsWith('http')
            ? item.goods_image
            : this.$baseURL + item.goods_image
        })
        this.goodsList = [...this.goodsList, ...res.data.list]
        this.noData = !this.goodsList.length
      }
    },
    // 添加购物车
    async addCart(item) {
      const res = await this.$http.post('/api/kuerp/order/index/addCart', {
        goods_id: item.id,
        goods_unit: item.unit_id,
        number: 1
      })
      if (res.code == 200) {
        uni.showToast({
          title: '添加成功',
          icon: 'success'
        })
      }
    },
    goodsType(id, name) {
      console.log('this.id', id)
      console.log('name', name)
      uni.navigateTo({
        url: `/pages/home/homeGoods/goodsTabs?titleName=${name}&id=${id}`
      })
    },
    getDetail(id) {
      uni.navigateTo({ url: `/pages/home/homeGoods/goodsDetail?id=${id}` })
    }
  },
  computed: {
    ...mapState(['priceStatus'])
  }
}
</script>

<style>
page {
  background-color: #fff;
  color: #111111;
}
</style>
<style lang="scss" scoped>
// 头部自定义
.head-box {
  width: 750rpx;
  height: 300rpx;
  background: #fe492f;
  .serch-box {
    position: fixed;
    top: 0;
    left: 0;
    width: 750rpx;
    background: #fe492f;
    z-index: 99999;
    padding-left: 24rpx;
    .search-input {
      width: 430rpx;
      height: 64rpx;
      display: flex;
      align-items: center;
      background: #ffffff;
      border-radius: 35rpx;

      .icon-sousuo {
        margin-left: 24rpx;
        margin-right: 20rpx;
      }
    }
    .title {
      display: flex;
      align-items: center;
      .contact {
        position: relative;
        margin-left: 32rpx;
        .icon-xiaoxi {
          color: #fff;
          font-size: 48rpx;
        }
        button {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
          opacity: 0;
          z-index: 99999999;
        }
      }
    }
  }
}
// 特价促销
.sale-box {
  width: 100%;
  margin-top: 20rpx;

  height: 268rpx;
  .sale-top {
    width: 100%;
    height: 60rpx;
    background: linear-gradient(180deg, #fff0f0 0%, #ffffff 100%);
    border-radius: 12rpx 12rpx 0 0;
    align-items: center;
    display: flex;
    image {
      width: 128rpx;
      margin-left: 24rpx;
    }
  }
  .sale-bottom {
    padding-top: 10rpx;
    height: 100%;
    background-color: #fff;
    height: 208rpx;

    .sale-goods-box {
      display: flex;
      .sale-items {
        .sale-item {
          margin-right: 36rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          &:first-child {
            margin-left: 24rpx;
          }
          &:last-child {
            margin-right: 24rpx;
          }
          image {
            width: 125rpx;
            height: 140rpx;
          }
          .sale-money {
            color: #fe3d23;
            font-weight: 600;

            text {
              &:first-child {
                font-size: 20rpx;
              }
              &:nth-child(2) {
                font-size: 24rpx;
              }
              &:last-child {
                font-size: 20rpx;
              }
            }
          }
        }
      }
    }
  }
}
/* #ifdef MP-WEIXIN */
scroll-view ::v-deep ::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}
/* #endif */

/deep/scroll-view {
  ::-webkit-scrollbar {
    width: 0;
    height: 0;
    background-color: transparent;
  }
}
/deep/wx-swiper .wx-swiper-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 10rpx;
}
/deep/wx-swiper .wx-swiper-dot-active {
  width: 32rpx;
  height: 12rpx;
  border-radius: 10rpx;
  background: #eb544d;
}

// 导航栏
.tabs-box {
  margin-top: 30rpx;
}

.pop-box {
  padding-bottom: 32rpx;
  .pop-top {
    background: linear-gradient(126deg, #fe8647 0%, #f74529 100%);
    color: #fff;
    font-size: 45rpx;
    font-weight: 500;
    width: 100%;
    height: 120rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .pop-center {
    padding: 32rpx 32rpx 44rpx;
    line-height: 40rpx;
  }
  .pop-bottom {
    padding: 0 50rpx;
    view {
      background-color: #fe492f;
      font-size: 36rpx;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 90rpx;
      border-radius: 40rpx;
    }
  }
}

// 轮播图
.swiper-box {
  padding: 0 24rpx;
}

// 商品分类
.category-box {
  // padding: 0 42rpx;
  height: 260rpx;
  /deep/wx-swiper {
    wx-swiper-item {
      padding: 0 35rpx;
    }
  }
  swiper {
    height: 260rpx;

    swiper-item {
      display: flex;
      align-items: center;
      .category-item {
        margin-right: 45rpx;
        width: 102rpx;
        text-align: center;
        image {
          width: 100rpx;
          height: 100rpx;
        }
        .item-name {
          margin-top: 12rpx;
          font-size: 24rpx;
          line-height: 34rpx;
        }
      }
    }
  }
}

// 底部
.bottom-box {
  overflow: hidden;
  padding: 0 24rpx 20rpx;
  margin-top: 20rpx;
  background-color: #f7f7f7;
  border-radius: 30rpx 30rpx 0rpx 0rpx;
}

// 公告
.notice-box {
  margin-top: 20rpx;
  width: 702rpx;
  height: 72rpx;
  background: #ffffff;
  border-radius: 36rpx;
  display: flex;

  align-items: center;
  .notice-img {
    display: flex;
    align-items: center;
    margin-left: 4rpx;
    image {
      width: 60rpx;
      height: 60rpx;
    }
  }
  .notice-title {
    margin-left: 10rpx;
    font-size: 32rpx;
    color: #333333;
  }

  .notice-scroll {
    height: 72rpx;
    flex: 1;
  }
}

// 商品
.goods-box {
  min-height: 500rpx;
  background-color: #f7f7f7;
  display: flex;
  flex-wrap: wrap;
  .item {
    position: relative;
    overflow: hidden;
    margin-top: 20rpx;
    width: 340rpx;
    height: 540rpx;
    background: #ffffff;
    border-radius: 12rpx;
    &:nth-child(odd) {
      margin-right: 22rpx;
    }
    .item-img {
      width: 340rpx;
      height: 340rpx;
      image {
        width: 340rpx;
        height: 340rpx;
      }
    }
    .item-name {
      margin-top: 14rpx;
      padding: 0 20rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    .item-price {
      position: absolute;
      left: 0;
      bottom: 22rpx;
      display: flex;
      width: 340rpx;
      justify-content: space-between;
      align-items: center;
      padding: 0 24rpx 0 20rpx;
      .price {
        .price-box {
          .price1 {
            font-size: 25rpx;
            color: #fe3d23;
            font-weight: 600;
          }
          .price2 {
            font-size: 32rpx;
            color: #fe3d23;
            font-weight: 600;
          }
          .digit {
            font-size: 25rpx;
            color: #fe3d23;
            font-weight: 600;
          }
        }
      }
      .t-icon-a- {
        width: 44rpx;
        height: 44rpx;
      }
    }
  }
}

.bandTip {
  position: fixed;
  width: 750rpx;
  height: 120rpx;
  background: #fe492f;
  bottom: 0;
  left: 0;

  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  view {
    &:first-child {
      font-weight: 500;
      color: #ffffff;
    }
    &:last-child {
      width: 160rpx;
      height: 72rpx;
      border-radius: 36rpx;
      border: 1rpx solid #ffffff;
      font-weight: 500;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
